package cn.edu.zafu.bigdata.Yum;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat; // 导入SimpleDateFormat类
import java.util.Date;

public class Server1 {
    public static void main(String[] args) throws IOException {
        int port = 9876; // 服务端端口号
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[1024];
        byte[] sendData = new byte[1024];

        while (true) {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Server received: " + sentence);

            // 获取当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(new Date());

            // 发送时间给客户端
            InetAddress IPAddress = receivePacket.getAddress();
            sendData = currentTime.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, receivePacket.getPort());
            serverSocket.send(sendPacket);
            System.out.println("Server sent: " + currentTime);
        }
    }
}